package com.yupi.springbootinit.redis;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.ThrowUtils;
import org.redisson.Redisson;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.scheduling.concurrent.DefaultManagedAwareThreadFactory;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class RedisLimit {

	public static void main(String[] args) {
		List<String> list = Arrays.asList("xlsx", "xls");
		ThrowUtils.throwIf(!list.contains("xls"), ErrorCode.PARAMS_ERROR,"文件格式合格");
	}

	public void testRedisLimit(){
		ExecutorService executorService = Executors.newFixedThreadPool(10, new DefaultManagedAwareThreadFactory());
		Config config=new Config();
		config.useSingleServer().setAddress("redis://127.0.0.1:6379");
		RedissonClient client= Redisson.create(config);
		RRateLimiter rateLimiter=client.getRateLimiter("rate_limiter");
		//就是每秒生成5个令牌  ---> 也就强制了每秒最多处理5个请求->当一秒内来了超多5个请求，多余的请求被拒绝
		rateLimiter.trySetRate(RateType.PER_CLIENT,5,1, RateIntervalUnit.MINUTES);
		for (int i=0;i<10;i++){
			executorService.execute(new Runnable() {
				@Override
				public void run() {
					if(rateLimiter.tryAcquire()) {
						System.out.println("线程"+Thread.currentThread().getId()+"进入数据区："+System.currentTimeMillis());

					}else {
						System.out.println("限流器限流了");
					}
				}
			});
		}
	}

}
